package lib

import "strings"

func init() {
	Probs = append(Probs, Problem{
		Num:         290,
		Discription: "字符串模板匹配（字符规律）",
		Level:       1,
		Labels: map[string]int{
			"哈希表":  1,
			"双射": 1,
		},
	})
}

//每个x对应为一个唯一的y，每个y对应一个唯一的x
//两个哈希表保证双射
func WordPattern(pattern string, s string) bool {
	words := strings.Split(s, " ")
	if len(words) != len(pattern) {
		return false
	}

	fx := make(map[byte]string, 0)
	rx := make(map[string]byte, 0)
	for i := range pattern {
		fxWord, exist1 := fx[pattern[i]]
		rxCh, exist2 := rx[words[i]]
		if !exist1 && !exist2 {
			fx[pattern[i]] = words[i]
			rx[words[i]] = pattern[i]
			continue
		}

		if exist1 && exist2 && fxWord == words[i] && rxCh == pattern[i] {
			continue
		}

		return false
	}

	return true
}